import { forwardRef, useState, useEffect, useImperativeHandle } from 'react'
import { InbizIcon } from '@inbiz/utils';
import { TextWidget } from '@inbiz/react';
import { Form } from 'antd'
import { getComponent, filterkeys } from '../../../../../../SearchEngine/searchCommon'
import FormItemTitle from '../components/FormItemTitle'
import { getDmsSearchData } from '../../../../../../SearchEngine/preview/web/components/SmallPanelView/SmallPanelAdvancedSearch/utils'
import './index.less'
export default forwardRef(function MetadataArea(props: any, ref) {
  const { config, $params, params, searchEngineData, categorySearchWhere, categoryLevel } = props
  const [form] = Form.useForm()
  const [metaDataItems, $metaDataItems] = useState<any>([])
  const onValuesChange = () => {
    categoryLevel.current = -1
    let searchStr = ''
    const changedValues = form.getFieldsValue()
    let metaData = Object.values(changedValues).filter(item => item && item.value)
    searchStr += ` AND ${getDmsSearchData(metaData)}`
    const newSearchWhere = searchStr.slice(5)?config.resultsSearchCriteria + ' AND ' + searchStr.slice(5) : config.resultsSearchCriteria
    // 元数据搜索
    const SearchWhere = categorySearchWhere ? categorySearchWhere + ' AND ' + newSearchWhere : newSearchWhere;
    $params({ ...params, PageIndex: 1, SearchWhere })
  }
  const initmetadataitems = () => {
    const orignmetaData = searchEngineData.metaData
    if (orignmetaData && (orignmetaData?.file || orignmetaData?.folder)) {
      const metaData = config.IndexName == 'file' ? orignmetaData.file : orignmetaData.folder
      // 筛选出默认的, 不显示出来, 目前只筛选小视图
      const newItems = metaData.filter(item => !filterkeys.includes(item.key.toLowerCase()))
      $metaDataItems(newItems)
    }
  }
  useEffect(() => {
    if (config.IndexName == 'file' || config.IndexName == 'folder') {
      initmetadataitems()
    }
  }, [config, searchEngineData])

  useImperativeHandle(ref, () => ({
    resetAll: () => {
      if (metaDataItems.length > 0) {
        const initData = metaDataItems.map(item => ({ [item.key]: { ...item, value: '' } })).reduce((prev, next) => ({ ...prev, ...next }))
        form.setFieldsValue(initData)
        onValuesChange()
      }
    },
    metaForm: form
  }))
  const clearField = (item) => {
    form.setFieldValue(item.key, {
      ...item,
      value: ''
    })
    onValuesChange()
  }
  useEffect(() => {
    for (let index = 0; index < metaDataItems.length; index++) {
      const element = metaDataItems[index];
      form.setFieldValue(element.key, element)
    }
  }, [metaDataItems])
  if (metaDataItems.length == 0) {
    return null
  }


  return (
    <div className='buildInArea'>
      <div style={{ color: '#999', height: 20, marginBottom: 10, marginLeft: 7 }}><InbizIcon type='icon-ic-daohang-shujuyuan' style={{ color: '#999' }} /><TextWidget>SearchResultEngine.otherCondition</TextWidget></div>
      <Form onValuesChange={(val) => onValuesChange(val)} form={form} onSubmitCapture={(e) => { e.preventDefault(); return false }}>
        {
          metaDataItems.map((item, index) => {
            return <div key={item.key}>
              <FormItemTitle title={item.label} config={config} showClear={params.SearchWhere.includes(item.key)} clearField={() => clearField(item)} />
              <Form.Item
                name={item.key}
                initialValue={item}
              >
                {
                  getComponent(item)
                }
              </Form.Item>
            </div>
          })
        }
      </Form>
    </div>
  )
})
